package com.ioudi.digu.flex.message;

import org.springframework.flex.core.MessageInterceptor;
import org.springframework.flex.core.MessageProcessingContext;

import com.ioudi.digu.dsdistribute.IDatasourceDistribute;
import com.ioudi.digu.memcached.MemcachedClient;
import com.ioudi.digu.vo.User;

import flex.messaging.FlexContext;
import flex.messaging.client.FlexClient;
import flex.messaging.messages.Message;

public class MessageDSInterceptor implements MessageInterceptor
{
   
	private IDatasourceDistribute datasourceDistribute;
	
	private MemcachedClient memcachedClient;
	

	public Message postProcess(MessageProcessingContext context,
			Message inputMessage, Message outputMessage)
	{
		return outputMessage;
	}

	public Message preProcess(MessageProcessingContext context,
			Message inputMessage)
	{
		FlexClient client = FlexContext.getFlexClient();
		if(client != null)
		{
			String user = String.valueOf(client.getAttribute("user"));
			if(user != "null")
			{
				Object db = memcachedClient.get(MemcachedClient.ID_USER_DB + user);
				String dsName = String.valueOf(db);
				if(db == null)
				{
					dsName = datasourceDistribute.lookupDatasource(user, false);			
				}
				if(dsName != null)
				{
					datasourceDistribute.useDatasouce(dsName);	
				}
				//can't find a db for the user. so reject the request
				else
				{
					return null;
				}
			}
		}
		return inputMessage;
	}
	
	public IDatasourceDistribute getDatasourceDistribute()
	{
		return datasourceDistribute;
	}

	public void setDatasourceDistribute(IDatasourceDistribute datasourceDistribute)
	{
		this.datasourceDistribute = datasourceDistribute;
	}
	
	public MemcachedClient getMemcachedClient()
	{
		return memcachedClient;
	}

	public void setMemcachedClient(MemcachedClient memcachedClient)
	{
		this.memcachedClient = memcachedClient;
	}


}
